import { createRouter, createWebHistory } from 'vue-router'
import AppLayout from '@/components/layout/AppLayout.vue'
import IndexView from '@/views/IndexView.vue'
import { useTokenStore } from "@/stores/mytoken"

// const store = userTokenStore()

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/login/LoginView.vue'),
    },
    {
      path: '/',
      name: 'home',
      component: AppLayout,
      meta:{ requiresAuth:true },
      children:[
        {
          path: '',
          name: 'index',
          component: IndexView
        },
        {
          path: '/about',
          name: 'about',
          // route level code-splitting
          // this generates a separate chunk (About.[hash].js) for this route
          // which is lazy-loaded when the route is visited.
          component: () => import('../views/AboutView.vue'),
        },
        {
          path:"/:xxx(.*)*",
          name:"ErrorPage",
          component:()=>import("@/views/ErrorPage.vue")
        }
      ]
    },
  ],
})

router.beforeEach((to,from,next)=>{
  if(to.meta.requiresAuth){
    const store = useTokenStore()
    if (!store.token.access_token) {
      next({name:"login", query:{ redirect: to.fullPath }})
    }else {
      next()
    }
  }else{
    next()
  }
})

export default router
